//declare sockaddr socket bind listen accept socklen_t
//#include <sys/types.h>
#include <sys/socket.h>
//declare htons inet_aton inetntoa, must before linux/in.h
#include <arpa/inet.h>
//declare sockaddr_in
#include <linux/in.h>
//declare NULL printf
#include <stdio.h>
//declare strlen
#include <string.h>
//declare toupper
#include <ctype.h>
//decl read write
#include <unistd.h>

#define SERVER_PORT 8888
#define SERVER_IP "127.0.0.1"
#define MAXBACKLOG 20
#define MAXBUF 1024

typedef struct sockaddr SockAddr;
typedef struct sockaddr_in SockAddrIn;

static SockAddrIn s_addr_in, s_addr_in_c; // server addr and client addr
static int sfd, conted_fd; //socket for listen and socket for connect
static char const wl[] = "Welcome!\n"; //msg to send 
static socklen_t len; 
static char buf[MAXBUF];
static socklen_t size;

static void str2upper(char s[], int len) {
	int i;
	for(i=0; i<len; i++) {
		s[i] = toupper(s[i]);
	}
}

int main(void)
{
	s_addr_in.sin_family = AF_INET;
	s_addr_in.sin_port = htons(SERVER_PORT);
    //
	inet_aton(SERVER_IP, &s_addr_in.sin_addr);
	sfd = socket(AF_INET, SOCK_STREAM, 0);
	bind(sfd, (SockAddr*)&s_addr_in, sizeof(s_addr_in));
	listen(sfd, MAXBACKLOG);
	size = sizeof(s_addr_in_c);
	conted_fd = accept(sfd, (SockAddr*)&s_addr_in_c, &size);
	printf("Connected from:%s:%d\n", 
           inet_ntoa(s_addr_in_c.sin_addr), //client ip
           ntohs(s_addr_in_c.sin_port));    //client port
	write(conted_fd, wl, strlen(wl));
	len = read(conted_fd, buf, MAXBUF);
	str2upper(buf, len);
	write(conted_fd, buf, len);
	close(conted_fd);
	close(sfd);
	return 0;
}
